﻿using System.Web;
using System.Data;
using System;
using System.Text;
using System.Web.Script.Serialization;

namespace Vincent
{
    /// <summary>
    /// json数据
    /// </summary>
    public class _Json
    {
        /// <summary>
        /// 要转换成json的DataTable
        /// </summary>
        public DataTable dt;

        /// <summary>
        /// 日期格式,默认是"yyyy-MM-dd"格式,
        /// 需要显示完整格式只需将该属性置为""
        /// </summary>
        public string DateFormat = "yyyy-MM-dd";

        /// <summary>
        /// 是否包含UBB语法
        /// </summary>
        public bool IsUBB = false;

        /// <summary>
        /// 是否转换时间数据 0 是 1 否
        /// </summary>
        public int IsDateChange = 0;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dt"> 要转换成json的DataTable </param>
        public _Json(DataTable dt)
        {
            this.dt = dt;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dt"> 要转换成json的DataTable </param>
        public _Json(DataTable dt, int _IsDateChange)
        {
            this.dt = dt;
            this.IsDateChange = _IsDateChange;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dt"> 要转换成json的DataTable </param>
        /// <param name="IsUBB"> 是否包含UBB语法 </param>
        public _Json(DataTable dt, bool IsUBB)
        {
            this.dt = dt;
            this.IsUBB = IsUBB;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dt"> 要转换成json的DataTable </param>
        /// <param name="DateFormat"> 日期格式,默认是"yyyy-MM-dd"格式,需要显示完整格式只需将该属性置为""</param>
        public _Json(DataTable dt, string DateFormat)
        {
            this.dt = dt;
            this.DateFormat = DateFormat;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dt"> 要转换成json的DataTable </param>
        /// <param name="IsUBB"> 是否包含UBB语法 </param>
        /// <param name="DateFormat"> 日期格式,默认是"yyyy-MM-dd"格式,需要显示完整格式只需将该属性置为""</param>
        public _Json(DataTable dt, bool IsUBB, string DateFormat)
        {
            this.dt = dt;
            this.IsUBB = IsUBB;
            this.DateFormat = DateFormat;
        }

        /// <summary>
        /// 转换成json，此处转换的结果是一个json数组包括了"[]"，转换后需要加一个键
        /// </summary>
        /// <returns></returns>
        public string ToJson()
        {
            if (dt == null)
                return "[]";

            string colname = "";
            string jsonstr = "";
            string value = "";
            jsonstr = "[";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonstr += "{";
                string tempFormatJson = ""; // 文件格式字段
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    colname = dt.Columns[j].ColumnName.ToLower();
                    value = dt.Rows[i][j].ToString().Replace("'", "&apos;").Replace("\"", "").Replace("\n", "").Replace("\r", "").Replace("\0", "").Replace("\\", "\\\\");

                    if (this.IsDateChange != 1)
                    {
                        if (dt.Columns[j].DataType.Name.ToLower() == "datetime")
                            value = _Convert.ToDateTime(value).ToString(DateFormat);
                    }
                    if (dt.Columns[j].DataType.Name.ToLower() == "string")
                        value = HttpUtility.HtmlEncode(HttpUtility.HtmlDecode(value));

                    jsonstr += colname + ":'" + value + "'";
                    if (j < dt.Columns.Count - 1)
                        jsonstr += ",";
                }
                jsonstr += tempFormatJson;
                jsonstr += "}";
                if (i < dt.Rows.Count - 1)
                    jsonstr += ",";
            }
            jsonstr += "]";
            return jsonstr;
        }

        /// <summary>
        /// 转换为json数据
        /// </summary>
        /// <param name="itemvalue"> 需要过滤的数据 </param>
        /// <returns></returns>
        public string ToJson(string itemvalue)
        {
            if (dt == null)
                return "[]";

            string colname = "";
            string jsonstr = "";
            string value = "";
            jsonstr = "[";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (itemvalue.Contains(dt.Rows[i]["item"].ToString()))
                    continue;

                jsonstr += "{";
                string tempFormatJson = ""; // 文件格式字段
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    colname = dt.Columns[j].ColumnName.ToLower();
                    value = dt.Rows[i][j].ToString().Replace("'", "&apos;").Replace("\"", "").Replace("\n", "").Replace("\r", "").Replace("\0", "").Replace("\\", "\\\\");

                    if (this.IsDateChange != 1)
                    {
                        if (dt.Columns[j].DataType.Name.ToLower() == "datetime")
                            value = _Convert.ToDateTime(value).ToString(DateFormat);
                    }
                    if (dt.Columns[j].DataType.Name.ToLower() == "string")
                        value = HttpUtility.HtmlEncode(HttpUtility.HtmlDecode(value));

                    jsonstr += colname + ":'" + value + "'";
                    if (j < dt.Columns.Count - 1)
                        jsonstr += ",";
                }
                jsonstr += tempFormatJson;
                jsonstr += "}";
                if (i < dt.Rows.Count - 1)
                    jsonstr += ",";
            }
            jsonstr += "]";
            return jsonstr;
        }

        #region 静态方法

        /// <summary>
        /// 把对象集合序列化 JSON 字符串 
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="items">对象实体</param>
        /// <returns>JSON字符串</returns>
        public static string GetJson<T>(System.Collections.Generic.IEnumerable<T> items) where T : class, new()
        {
            if (items == null)
                throw new NullReferenceException("序列化对象不能为null!");
            System.Text.StringBuilder st = new System.Text.StringBuilder();
            try
            {
                StringBuilder sb = new StringBuilder();
                var jsonSerializer = new JavaScriptSerializer();
                jsonSerializer.Serialize(items, sb);
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }  

        #endregion

    }

}
